package com.ly.gof.structure.flyweight;

import java.util.HashMap;

/**
 * @author liuyang
 * @des 享元工厂（Flyweight Factory）角色：负责创建和管理享元角色。当客户对象请求一个享元对象时，享元工厂检査系统中是否存在符合要求的享元对象，
 * 如果存在则提供给客户；如果不存在的话，则创建一个新的享元对象。
 * @Version 1.0
 * @Date: 26/07/2021 14:29
 */
public class FlyweightFactory {

    //具体享元就是的缓存存储对象 可以是任意集合对象 可以使map 也可以是list
    private HashMap<String, Flyweight> flyweights = new HashMap<String, Flyweight>();

    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = (Flyweight)flyweights.get(key);
        if (flyweight != null) {
            System.out.println("具体享元" + key + "已经存在，被成功获取！");
        } else {
            flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}
